package woaini.fenger.core.utils;

import lombok.experimental.UtilityClass;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.MultimediaInfo;
import ws.schild.jave.process.ProcessWrapper;
import ws.schild.jave.process.ffmpeg.DefaultFFMPEGLocator;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 音频工具
 *
 * @see woaini.fenger.core.utils.AudioTool
 * @author yefeng {@code @Date} 2023-05-16 16:50:39
 */
@UtilityClass
public class AudioTool {

  /**
   * @MethodName convertAudio
   *
   * @param source 输入
   * @param target 输出
   * @author yefeng {@date 2024-01-24 10:31:42}
   * @since 1.0
   * @return boolean 转换音频
   */
  public boolean convertAudio(File source, File target){
    String outputFormat = getSuffix(target.getName());
    String inputFormat = getSuffix(source.getName());
    try {
      // 设置音频属性
      AudioAttributes audio = new AudioAttributes();
      audio.setBitRate(16000);
      audio.setSamplingRate(16000);
      audio.setChannels(1);
      if(inputFormat.equals("wav")) {
        audio.setCodec("pcm_s16le");
      }else if(inputFormat.equals("mp3")) {
        audio.setCodec("libmp3lame");
      }else if(inputFormat.equals("amr")){
        audio.setCodec("libvo_amrwbenc");
      }
      // 设置转码属性
      EncodingAttributes attrs = new EncodingAttributes();
      attrs.setInputFormat(inputFormat);
      attrs.setOutputFormat(outputFormat);
      attrs.setAudioAttributes(audio);
      // 音频转换格式类
      Encoder encoder = new Encoder();
      // 进行转换
      encoder.encode(new MultimediaObject(source), target, attrs);
      return true;
    } catch (IllegalArgumentException | EncoderException e)  {
      e.printStackTrace();
    }
    return false;
  }


  private String getSuffix(String outputFormatPath) {
    return outputFormatPath.substring(outputFormatPath.lastIndexOf(".") + 1);
  }

  public static void main(String[] args) throws IOException {
    File source = new File("/home/yefeng/IdeaProjects/otherBranches/wind/temp/response.wav");
    File target = new File("/home/yefeng/IdeaProjects/otherBranches/wind/temp/response.pcm");
    convertAudio(source, target);
  }
}
